from logging import Logger

from google.protobuf import text_format
from google.protobuf import json_format

logger = Logger('DrsuOperate').getlog()


class ProtobufFIle():
    # protobuf文件处理
    def __init__(self, conf_file, message_obj):
        """
            初始化
        :param conf_file: 需要解析的protobuf文件路径
        :param message_obj: protobuf对应的proto message对象
        """
        self.conf_file = conf_file
        self.message_obj = message_obj
        self.message = None

    def read_conf(self):
        try:
            with open(self.conf_file, "r", encoding='utf-8') as fp:
                text = fp.read()
            self.message = text_format.Parse(text, self.message_obj)
            logger.info('读取配置文件 {} 成功'.format(self.conf_file))
        except Exception as e:
            logger.error('文件读取失败： {}'.format(str(e)))
            return False
        return True

    def write_conf(self):
        try:
            with open(self.conf_file, "w", encoding='utf-8') as fp:
                fp.write(text_format.MessageToString(self.message))
            logger.info('写入配置文件 {} 成功'.format(self.conf_file))
        except Exception as e:
            logger.error('文件写入失败： {}'.format(str(e)))
            return False
        return True

    def convert_to_dict(self):
        if not self.message:
            self.read_conf()
        try:
            message_dict = json_format.MessageToDict(self.message)
            logger.info('配置转换为字典格式成功 {}'.format(message_dict))
        except Exception as e:
            logger.error('配置文件转换为字典格式失败： {}'.format(str(e)))
            return False
        return message_dict

    def convert_from_dict(self, dict_obj):
        self.message = json_format.ParseDict(dict_obj, self.message_obj)


if __name__ == '__main__':
    dag_camera = r'\dag_camera.config'

    dag_camera_msg = dag_camera_protobuf_pb2.DagCamera()
    protobuf_read = ProtobufFIle(dag_camera, dag_camera_msg)
    protobuf_read.convert_to_dict()
